package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.example.JavaBean.Student;
import org.example.bean.SecurityStudentDetails;
import org.example.mapper.StudentMapper;
import org.example.service.StudentService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Auther:Liu
 * @Testname:StudentServiceImpl
 * @Date:2025/9/16 22:02
 */
@Slf4j
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService, UserDetailsService {
    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("开始执行loadUserByUsername的登陆方法");
        // 1. 校验账号在数据库中是否存在
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", username);
        Student securityUser = baseMapper.selectOne(queryWrapper);
        if (securityUser == null) {
            throw new UsernameNotFoundException("账号不存在");
        }
        // 2. 获取到权限和加密后的密码
        String password = securityUser.getPassword();
        password = passwordEncoder.encode(password);
        securityUser.setPassword(password);
        // ROLE_ 代表角色
        List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("manager02", "manager03", "ROLE_role02");
        // 3. 返回封装user对象（UserSecurityDetails）
        SecurityStudentDetails securityStudentDetails = new SecurityStudentDetails();
        securityStudentDetails.setStudent(securityUser);
        securityStudentDetails.setPermissionValueList(authorities);
        return securityStudentDetails;
    }
}
